import requests
from lxml import etree
import os


'''
检测文件是否需要更新
需要更新，返回1
不需要更新，返回0
'''
def Update_detection(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36 Edg/91.0.864.71'
    }
    response = requests.get(url=url, headers=headers).text
    key_tree = etree.HTML(response)

    #更新关键词
    keywords = key_tree.xpath('//*[@id="git-project-info"]/div[1]/span[1]/a//text()')[0]
    update_state = 1

    with open('config/update.ini','r',encoding='utf-8') as fp:
        key = fp.readline()
        if key == keywords:
            update_state = 0
        else:
            update_state = 1
            with open('config/update.ini','w',encoding='utf-8') as fp:
                fp.write(keywords)
    return update_state


'''
获取更新的内容

readme文件内容读取形式错误，需要修改
'''
def Update_init(url):
    # UA伪装
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36 Edg/91.0.864.71'
    }
    response = requests.get(url=url, headers=headers)
    #检测连接情况
    if response.status_code == 200:
        print('连接成功')
        page_text = response.content
        gitee_tree = etree.HTML(page_text)

        for value in range(2,100,2):
            try:
                #获取文件名称
                filename = gitee_tree.xpath('//*[@id="tree-slider"]/div['+str(value) +']/div[1]/a/@title')[0]

                #获取对应文件url
                filename_url = 'https://gitee.com/' + gitee_tree.xpath('//*[@id="tree-slider"]/div['+str(value) +']/div[1]/a/@href')[0]

                #进入文件，读取文件内容
                response_next_page  = requests.get(url=filename_url, headers=headers).content
                next_gitee_tree = etree.HTML(response_next_page)

                #读取文件数据，并写入
                filename_text = next_gitee_tree.xpath('//*[@id="tree-content-holder"]/div/div[3]/div/div[2]/pre//text()')

                with open('config/' +filename, 'w', encoding='utf-8') as fp:
                        for main in filename_text:
                            fp.write(main)
            except:
                break


    elif response.status_code == 404:
        print("连接失败")





if __name__ == '__main__':

    #对应公开仓库的url
    url = 'https://gitee.com/lala-xiaoxin/update-test'

    if Update_detection(url) == 1:
        print('文件正在升级，请稍后')
        Update_init(url)
    else:
        print('文件不需要升级')


